import * as socket from 'atmosphere.js';
import config from '@/config';
import tokenUtil from '@/utils/token';

export default {

    mySocket: null,

    initSocket(successFun, headers = {}) {
        const prefix = process.env.NODE_ENV === "production" ? "/prod-api" : "/dev-api";
        const url = prefix + '/common/socket';
        console.log("初始化 WEB_SOCKET" + url)
        let userToken = tokenUtil.getUserToken();
        if (userToken) {
            headers[config.API_TOKEN_NAME] = config.API_TOKEN_PREFIX + userToken;
            headers[config.SOCKET_USER_ID] = tokenUtil.getUserId();
            headers[config.SOCKET_USER_INFO] = tokenUtil.getLoginName();
        }
        this.initFullSocket(url, headers, successFun, (response) => {
            console.log("socket 自定义错误方法：");
            console.log(response)
        })
    },

    initFullSocket(url, headers, successFun, errorFun) {
        let request = {
            url: url,
            contentType: "application/json",
            transport: 'websocket',
            logLevel: 'error',
            reconnectInterval: 5000,
            fallbackTransport: 'long-polling',
            headers: headers
        };

        // 连接打开时
        request.onOpen = function (response) {
            console.log("打开 socket 连接 ");
            console.log(response)
        };

        // 重新连接时
        request.onReconnect = function (request, response) {
            console.log("重新连接 socket ");
            console.log(response)
        };

        // 收到推送消息时
        request.onMessage = function (response) {
            // body 即为收到的消息内容
            let body = response.responseBody;
            try {
                if (typeof successFun == 'function') {
                    successFun(JSON.parse(body));
                }
            } catch (e) {
                if (typeof errorFun == 'function') {
                    errorFun(response);
                }
                console.log('socket catch 异常 ');
                console.log(response)
            }
        };

        // 发生错误时
        request.onError = function (response) {
            if (typeof errorFun == 'function') {
                errorFun(response);
            }
            console.log('socket 错误 ');
            console.log(response)
        };

        if (!this.mySocket) {
            this.mySocket = socket.subscribe(request);
        }
    },

}